<template>
  <div class="user">
    <!-- 搜索框 -->
    <div class="search">
      <div class="input">
        <el-input v-model="searchName" clearable placeholder="请输入用户名或真实姓名" @keyup.enter.native="getNames" />
      </div>
      <el-button type="primary" icon="el-icon-search" @click="getName()"/>
    </div>

    <!-- 中间表格 -->
    <div class="table">
      <el-table :data="tableData" border highlight-current-row>
        <el-table-column align="center" fixed prop="date" label="序号">
          <template slot-scope="scope">
            <span>{{ (page-1 )* pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="用户名">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="province" label="真实姓名">
          <template slot-scope="scope">
            <span>{{ scope.row.realName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              disabled
              @change="changeStatus"/>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime | fmtdate }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" min-width="170">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button type="text" style="margin-right:15px;" @click="handleEdit(scope.$index, scope.row)">
              绑定角色</el-button>
            <el-dialog :title="editData.username" :visible.sync="dialogTableVisible" :modal="false" :model="editData">
              <el-form ref="editFrom" :model="editData" :rules="editRules">
                <el-form-item :label-width="formLabelWidth" label="角色：" prop="roleIdList">
                  <template>
                    <el-checkbox-group v-model="editData.roleIdList">
                      <el-checkbox v-for="(v, index) in allRoles" :label="v.id" :key="index" size="small">{{ v.name }}
                      </el-checkbox>
                    </el-checkbox-group>
                  </template>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogTableVisible = false">取 消</el-button>
                <el-button type="primary" @click.stop="editor()">确 定</el-button>
              </div>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 页码 -->
    <div class="pages">
      <template>
        <div class="block">
          <el-pagination
            :current-page="page"
            :page-size="pageSize"
            :total="total"
            background
            layout="prev, pager, next"
            @current-change="handleCurrentChange"/>
        </div>
      </template>
    </div>
  </div>
</template>

<script>
import {
  UserPageFunc,
  UserAddFunc,
  UserDelIdFunc,
  UserChangePsdFunc,
  UserGetRoleListFunc,
  UserGetRoleIdFunc,
  UserChangeFunc
} from '../../api/user.js';
import {
  Message,
  MessageBox
} from 'element-ui';
export default {
  name: 'User',
  data() {
    return {
      dialogFormVisible: false, // 增加新用户弹窗默认不显示
      dialogTableVisible: false, //  编辑弹窗默认不显示
      dialogpsdVisible: false, //  修改密码弹窗默认不显示
      form: { // 存储增加用户数据
        password: '',
        realName: '',
        roleIdList: [],
        status: 1,
        username: '',
        passwordTwo: ''
      },
      rules: { // 验证规则
        realName: [{
          required: true,
          trigger: 'blur'
        }],
        username: [{
          required: true,
          trigger: 'blur'
        }],
        password: [{
          required: true,
          trigger: 'blur'
        }],
        passwordTwo: [{
          required: true,
          trigger: 'blur'
        }]
      },
      editData: { // 存储修改用户数据
        id: '',
        password: '',
        realName: '',
        roleIdList: [],
        status: '',
        username: ''
      },
      editRules: { // 验证规则
        username: [{
          required: true,
          trigger: 'blur'
        }],
        realName: [{
          required: true,
          trigger: 'blur'
        }]
      },
      changePsdData: { // 存储修改密码数据
        id: '',
        newPassword: '',
        newPasswordTwo: '',
        password: ''
      },
      psdRules: { // 验证规则
        newPassword: [{
          required: true,
          trigger: 'blur'
        }],
        newPasswordTwo: [{
          required: true,
          trigger: 'blur'
        }]
      },
      formLabelWidth: '100px',
      searchName: '', // 搜索框关键字
      allRoles: '', // 获取所有用户角色
      total: 0, // 数据总条数
      tableData: [], // 数据列表
      page: 1, // 当前页数
      pageSize: 8 // 当页数据条数
    };
  },
  created() {
    this.init(); // 获取后台数据
  },
  methods: {
    //  初始化
    init() {
      UserPageFunc(this.page, this.pageSize).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },
    // 点击回车键发起搜索
    getNames() {
      this.page = 1;
      this.tableData = [];
      this.total = 0;
      UserPageFunc(this.page, this.pageSize, this.searchName).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },
    // 点击搜索按钮
    getName() {
      this.page = 1;
      this.tableData = [];
      this.total = 0;
      UserPageFunc(this.page, this.pageSize, this.searchName).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },
    // 切换页码
    handleCurrentChange(val) {
      this.page = val;
      this.tableData = [];
      UserPageFunc(this.page, this.pageSize).then(result => {
        this.tableData = result.data.rows;
        this.total = result.data.total;
      });
    },
    // 获取所有角色
    getRoleList() {
      this.allRoles = '';
      UserGetRoleListFunc().then((res) => {
        const items = res.data;
        this.allRoles = items.map(v => {
          return {
            id: v.id,
            name: v.name
          };
        });
      });
    },
    /** ******************** 新增 *******************/
    // 点击添加按钮 出现弹窗
    add() {
      this.form = {
        password: '',
        realName: '',
        roleIdList: [],
        status: 1,
        username: '',
        passwordTwo: ''
      };
      this.dialogFormVisible = true;
      this.getRoleList();
      this.$nextTick(function() {
        this.$refs.from.resetFields(); // 移除校验结果
      });
    },
    // 点击增加用户弹窗 确定按钮
    addUser() {
      if (
        this.form.password == '' ||
          this.form.passwordTwo == '' ||
          this.form.realName == '' ||
          this.form.username == ''
      ) {
        Message({
          message: '请认真填写每一项',
          type: 'error',
          duration: 5 * 1000
        });
      } else if (this.form.password != this.form.passwordTwo) {
        Message({
          message: '两次密码输入不一致，重新输入',
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        UserAddFunc(
          this.form.password,
          this.form.realName,
          this.form.roleIdList,
          this.form.status,
          this.form.username
        )
          .then(res => {
            if (res.code == 200) {
              Message({
                message: '增加成功',
                type: 'success',
                duration: 5 * 1000
              });
              this.dialogFormVisible = false;
              this.init();
            }
            if (res.code == 500) {
              Message({
                message: '已存在此账号或未知错误',
                type: 'error',
                duration: 5 * 1000
              });
            }
          });
      }
    },
    /** ******************** 编辑 *******************/
    // 点击编辑按钮 出现弹窗
    handleEdit(index, row) {
      this.editData = Object.assign({ roleIdList: [] }, row);
      this.getRoleList();
      UserGetRoleIdFunc(this.editData.id).then((res) => {
        const item = res.data;
        item.map(v => {
          this.editData.roleIdList.push(v);
        });
      });
      this.dialogTableVisible = true;
      this.$nextTick(function() {
        this.$refs.editFrom.clearValidate(); // 移除校验结果
      });
    },
    // 点击编辑弹窗 确定按钮
    editor() {
      if (
        this.editData.realName == '' ||
          this.editData.username == ''
      ) {
        Message({
          message: '请认真填写每一项',
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        UserChangeFunc(
          this.editData.id,
          this.editData.realName,
          this.editData.roleIdList,
          this.editData.status,
          this.editData.username
        )
          .then(res => {
            if (res.code == 200) {
              Message({
                message: '修改成功',
                type: 'success',
                duration: 5 * 1000
              });
              // 关闭弹窗 刷新页面
              this.dialogTableVisible = false;
              this.init();
            }
            if (res.code == 500) {
              Message({
                message: '修改失败或未知错误',
                type: 'error',
                duration: 5 * 1000
              });
            }
          });
      }
    },
    /** ******************** 删除 *******************/
    // 点击删除按钮
    deleteRow(index, rows) {
      MessageBox.confirm(
        '确定删除吗？', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        const id = rows[index].id;
        UserDelIdFunc(id).then(res => {
          if (res.code == 200) {
            Message({
              message: '删除成功',
              type: 'success',
              duration: 5 * 1000
            });
            rows.splice(index, 1);
            this.page = 1;
            this.init();
          }
        });
      });
    },
    /** ******************** 修改密码 *******************/
    // 点击修改密码按钮 出现弹窗
    handleChangePsd(index, row) {
      this.dialogpsdVisible = true;
      this.changePsdData.id = row.id; // 获取用户对应id
      this.changePsdData.newPassword = '';
      this.changePsdData.newPasswordTwo = ''; // 清空上次编辑的数据
      this.$nextTick(function() {
        this.$refs.psdRules.resetFields(); // 移除校验结果
      });
    },
    // 点击修改密码弹窗 确定按钮
    changePsd() {
      if (this.changePsdData.newPassword != this.changePsdData.newPasswordTwo) {
        Message({
          message: '两次密码输入不一致',
          type: 'error',
          duration: 5 * 1000
        });
      } else if (this.changePsdData.newPassword == '' || this.changePsdData.newPasswordTwo == '') {
        Message({
          message: '密码不能为空',
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        UserChangePsdFunc(
          this.changePsdData.id,
          this.changePsdData.newPassword,
        )
          .then(res => {
            if (res.code == 200) {
              Message({
                message: '修改成功',
                type: 'success',
                duration: 5 * 1000
              });
              this.dialogpsdVisible = false;
            }
            if (res.code == 500) {
              Message({
                message: '修改失败或未知错误',
                type: 'error',
                duration: 5 * 1000
              });
            }
          });
      }
    },
    // 开关状态改变
    changeStatus() {
      // 先禁用，后期可能点击直接修改用户状态
    }
  }
};

</script>

<style lang="scss" scoped>
  .user {
    position: relative;
    height: calc(100vh - 50px);
    padding: 20px;
    margin: 0 100px;
  }

  /*搜索框*/
  .search {
    height: 40px;
    padding: 50px 0;

    .input {
      width: 240px;
      margin-right: 5px;
      float: left;
    }

    .add {
      margin-right: 172px;
      float: right;

      /* 放大添加图标 */
      .el-icon-circle-plus {
        transform: scale(3);
      }
    }
  }

  /*中间列表*/
  .table {
    max-height: 627px;
    margin-bottom: 50px;
  }

  /*分页*/
  .pages {
    float: right;
  }

  /* 重置多选框样式 */
  .el-checkbox-group {
    .el-checkbox {
      margin: 0;
      width: 25%;
      float: left;
      text-align: left;
    }
  }

  /* 编辑界面中开关位置 */
  .editor-switch {
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%)
  }

</style>
